<template>
  <div style="padding: 0px 100px;" class="flex">
    <div class="btn-group auto">
      <button type="button" class="btn btn-primary" @click="removeData(ids)">批量删除</button>
      <button type="button" class="btn btn-primary" @click="setUser()">设置用户</button>
      <button type="button" class="btn btn-primary" @click="$goto('edit', {data: data})">策略授权</button>
      <button type="button" class="btn btn-primary">移动资源</button>
    </div></br>
    <span>{{data.name}}</span></br>
    <div class="span">
      <data-grid :model='model'>
        <template partial='head'>
          <tr>
            <th colspan="5">角色管理</th>
          </tr>
          <tr>
            <th>全选<input type="checkbox" class="all-checked" v-model="checked" @click="$parent.$parent.isAll(checked)"></th>
            <th></th>
            <th>用户姓名</th>
            <th>删除</th>
          </tr>
        </template>
        <template partial='body'>
          <td><input type="checkbox"  v-model="$parent.$parent.ids" :value="row"></td>
          <td><img :src="$parent.$parent.imgsrc(row.f_icon)" alt=""></td>
          <td>{{row.name}}</td>
          <td><span class="glyphicon glyphicon-remove" @click="$parent.$parent.removeData([row])"></span></td>
        </template>
      </data-grid>
    </div>


    <!-- 设置用户模态框开始 -->
    <modal v-ref:modal :show.sync="setShow" :backdrop="false" class="auto">
      <header slot="modal-header" class="modal-header">
        <button type="button" class="close" @click="close"><span>&times;</span></button>
        <h4 class="modal-title">设置用户</h4>
      </header>
      <article slot="modal-body" class="modal-body modifystyle">
        <tree :model="usersData" v-ref:tree>
          <span partial>{{row.data.name}}
            <input type="checkbox" v-model="$parent.$parent.$parent.userids" :value="row.data.id">
          </span>
        </tree>
      </article>
      <footer slot="modal-footer" class="footerbtn">
        <button  type="button" class="btn btn-success" @click='save()'>保存</button>
      </footer>
    <modal>
    <!-- 设置用户模态框结束 -->
  </div>
</template>

<script>
import co from 'co'
import * as Util from '../Util'

// 页面加载前，获取角色下的用户
let gen = function * (self) {
  //self.model = yield self.$post('rs/search', '{source: `tool.getChildren($${self.data.id}$)`, userid: self.userid}',{resolveMsg: null, rejectMsg: null})
  self.model = yield self.$http.post('rs/search', {source: `tool.getChildren($${self.data.id}$)`, userid: self.userid},{resolveMsg: null, rejectMsg: null})
  //self.model = yield self.$http.post('rs/search',data)
  console.log(self.model.body)
  console.log("加载时获取的用户:")
  //var r = self.model.body.filter(function(element,index,self){
   // return self.id.indexOf(element.id) === index;
  //});
  //去重
  function arrayUnique2(arr, name) {
    var hash = {};
    return arr.reduce(function (item, next) {
      hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
      return item;
    }, []);
  }
  var r = arrayUnique2(self.model.body, "id")
  console.log(r)
  self.model.body = r
  //self.model.data.forEach((row) => {
  r.forEach((row) => {
    self.userids.push(row.id)
  })
}
// 删除当前角色写的用户
let deleteData = function * (self,data) {
  //yield self.$post('rs/data/deleteUser', {data: {ids: data, roleid: self.data.id}},{resolveMsg:null, rejectMsg:null})
  yield self.$http.post('rs/data/deleteUser', {data: {ids: data, roleid: self.data.id}}).then(function(res) {
    //console.log("删除")
    //console.log(res.bodyText)
    //self.$showMessage(res.bodyText)
    self.refresh()
  });
}
// 获取用户
let getUser = function * (self) {
  //let data = {source: `tool.getFullTree(this.getParent().getAllChildrens().where(row.getType() == $user$))`, userid: self.userid}
  //let ret = yield self.$http.post('/rs/search',{source: `tool.getFullTree(this.getParent().getAllChildrens().where(row.getType() == $user$))`, userid: self.userid})
  let ret = yield self.$http.post('/rs/search',{source: `tool.getFullTree(this.getParentByType($organization$).getAllChildrens().where(row.getType() == $user$))`, userid: self.userid})
  self.usersData = ret.data[0].children
  console.log(self.userData)
  self.setShow = true
}
// 设置用户后的保存
let saveUser = function * (self) {
  //let res = yield self.$post('rs/data/setUser', {data: {ids: self.userids, roleid: self.data.id}},{resolveMsg: null, rejectMsg: null})
  console.log("需要保存的用户")
  //var arr = ['apple','strawberry','banana','pear','apple','orange','orange','strawberry'];
  var r = self.userids.filter(function(element,index,self){
         return self.indexOf(element) === index;
  });
  console.log(r);
  console.log(self.userids)
  yield self.$http.post('rs/data/setUser',{data: {ids:r, roleid: self.data.id}}).then(function(res){
    if(res.status == 200){
      self.$showMessage(res.bodyText)
      self.setShow = false
      self.refresh()
    }else{
      self.$showMessage("保存失败")
    }
  });
  //yield self.$showMessage(res.data)

  /*if (res.data === '保存成功') {
    self.setShow = false
    // // 刷新数据

  }*/

}
export default {
  title: '角色管理',
  props: ['data', 'userid'],
  ready() {
    this.$parent.setTitle(this.data.name)
    this.refresh()
  },
  data () {
    return {
      ids: [],
      model: '',
      usersData: '',
      userids: [],
      setShow: false
    }
  },
  methods: {
    // 刷新数据
    refresh () {
      let g = gen(this)
      co(g)
    },
    add(name, row) {
      // console.log(name)
      let parent = this.datas
      let del = delete parent.children
      this.$goto(name, {parent: parent, row: row})
    },
    isAll (checked) {
      this.ids = []
      if (!checked) {
        this.model.data.forEach((row) => {
          this.ids.push(row)
        })
      }
    },
    imgsrc (name) {
      return Util.getImgsrc(name)
    },
    removeData (data) {
      let d = deleteData(this,data)
      co(d)
    },
    // 设置用户，弹出模态框设置用户getUser
    setUser () {
      let get = getUser(this)
      co(get)
    },
    // 关闭设置用户模态框
    close () {
      // this.$showMessage('哈哈哈啊哈哈')
      this.setShow = false
    },
    // 保存设置的用户
    save () {
      let s = saveUser(this)
      co(s)
    },
    // modify(row) {
    //   this.$goto("modify-function", {parentname: this.datas.name, parentid: this.datas.id, row: row})
    // }
  }
}
</script>
<style>
  .all-checked {
    vertical-align: text-top;
    margin-left: 10px !important;
  }
  td > .glyphicon {
    cursor: pointer;
  }
  th > input[type="checkbox"], td > input[type="checkbox"] {
    cursor: pointer;
  }
  .modifystyle div{
    margin-left: 0px;
    color: #000;
  }
  .modifystyle span {
    color: #000;
  }
  .modifystyle .list-group-item {
    background-color: #fff;
    border: none;
  }
  .modifystyle .list-group-item.active,
  .modifystyle  .list-group-item.active:hover,
  .modifystyle  .list-group-item.active:focus {
    background-color: #fff;
  }
</style>
